<script setup>
import { ref, watch } from "vue";
import { useRouter, useRoute } from "vue-router";

//ref 和 relative 的区别
const activeTab = ref(0);
const route = useRoute();
const router = useRouter();
const onTabChange = index => {
  switch (index) {
    case 0:
      router.push("/");
      break;
    case 1:
      router.push("/category");
      break;
    case 2:
      router.push("/publish");
      break;
    case 3:
      router.push("/cart");
      break;
    case 4:
      router.push("/profile");
      break;
  }
  //tab 切换事件
  if (index === activeTab.value) {
    const refreshEvent = new CustomEvent("tab-refresh", {
      detail: { tab: index }
    });

    window.dispatchEvent(refreshEvent);
  }
};


//监听路由变化 当第一个参数变化的时候，会触发第二个参数的回调函数
watch(
  () => route.path,
  newPath => {
    switch (newPath) {
      case "/":
        activeTab.value = 0;
        break;
      case "/category":
        activeTab.value = 1;
        break;
      case "/publish":
        activeTab.value = 2;
        break;
      case "/cart":
        activeTab.value = 3;
        break;
      case "/profile":
        activeTab.value = 4;
        break;
      default:
        activeTab.value = 0;
    }
  },
  { immediate: true }
);
</script>
<template>
  <div class="layout-page">
    <router-view />

    <van-tabbar v-model="activeTab" @change="onTabChange">
      <!-- 首页导航项 -->
      <van-tabbar-item icon="wap-home-o">首页</van-tabbar-item>

      <!-- 分类导航项 -->
      <van-tabbar-item icon="apps-o">分类</van-tabbar-item>

      <!-- 发布导航项 - 使用自定义图标 -->
      <van-tabbar-item>
        <template #icon>
          <div class="publish-btn">
            <span class="publish-plus">+</span>
          </div>
        </template>
        <span>发布</span>
      </van-tabbar-item>

      <!-- 购物车导航项 -->
      <van-tabbar-item icon="shopping-cart-o">购物车</van-tabbar-item>

      <!-- 我的导航项 -->
      <van-tabbar-item icon="manager-o">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<style lang="scss" scoped>
/* 发布按钮的特殊样式 */
.publish-btn {
  width: 44px;
  height: 44px;
  background: linear-gradient(
    135deg,
    var(--van-primary-color) 0%,
    #7986cb 100%
  );
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: -16px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
  position: relative;
  z-index: 1;

  &:active {
    transform: scale(0.95);
  }
}

.publish-plus {
  font-size: 24px;
  color: white;
  font-weight: bold;
}
</style>